const app = getApp();
const { request } = require('../../../utils/request');
const api = require('../../../utils/api.js');
const codeApi = require('../../../utils/codeApi.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    agentInfo: null,
    hierarchy: null,
    stats: null,
    expandedNodes: {} // 记录展开状态的节点ID
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 检查代理权限
    this.checkAgentPermission();
  },

  /**
   * 检查代理权限
   */
  checkAgentPermission() {
    const userId = wx.getStorageSync('userId');
    
    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '未登录或登录已过期，请先登录',
        showCancel: false,
        success: () => {
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
      return;
    }
    
    codeApi.checkPermission(userId)
    .then(res => {
      if (res.code === 0 && res.data && res.data.has_permission) {
        this.setData({
          agentInfo: res.data.agent_info || {}
        });
        
        // 获取团队层级结构
        this.fetchTeamHierarchy();
      } else {
        wx.showModal({
          title: '提示',
          content: '您暂无代理管理权限',
          showCancel: false,
          success: () => {
            wx.navigateBack();
          }
        });
      }
    })
    .catch(err => {
      console.error('检查权限失败', err);
      
      wx.showToast({
        title: '网络错误',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
    });
  },

  /**
   * 获取团队层级结构
   */
  fetchTeamHierarchy() {
    const { agentInfo } = this.data;
    
    if (!agentInfo || !agentInfo.id) {
      this.setData({ loading: false });
      return;
    }
    
    const params = {
      agent_id: agentInfo.id
    };
    
    this.setData({ loading: true });
    
    request(api.agent_team_hierarchy, 'GET', params)
    .then(res => {
      if (res.code === 0 && res.data) {
        this.setData({
          hierarchy: res.data.hierarchy || {},
          stats: res.data.stats || {},
          loading: false
        });
      } else {
        this.setData({ loading: false });
        wx.showToast({
          title: res.message || '获取团队层级结构失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error('获取团队层级结构失败', err);
      this.setData({ loading: false });
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    });
  },

  /**
   * 切换节点展开状态
   */
  toggleNode(e) {
    const { id } = e.currentTarget.dataset;
    const { expandedNodes } = this.data;
    
    const newExpandedNodes = { ...expandedNodes };
    
    if (newExpandedNodes[id]) {
      // 如果已展开，则收起
      delete newExpandedNodes[id];
    } else {
      // 如果已收起，则展开
      newExpandedNodes[id] = true;
    }
    
    this.setData({
      expandedNodes: newExpandedNodes
    });
  },

  /**
   * 查看代理详情
   */
  viewAgentDetail(e) {
    const { id } = e.currentTarget.dataset;
    
    if (id) {
      wx.navigateTo({
        url: `/pages/admin/team-member-detail/team-member-detail?id=${id}`
      });
    }
  },

  /**
   * 返回团队管理页面
   */
  goToTeamManagement() {
    wx.navigateTo({
      url: '/pages/admin/team/team'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 如果已经有代理信息，刷新团队层级结构
    if (this.data.agentInfo) {
      this.fetchTeamHierarchy();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.fetchTeamHierarchy();
    wx.stopPullDownRefresh();
  }
}) 